#!/usr/bin/env python

import wx
import messaging.sms

import __message as message

import resource as r

class Message(wx.Panel):
    '''Message class
    
    @author Julot <andy.julot@gmail.com>
    @since Monday, February 27, 2012. 02:24 PM'''
    
    def __init__(self, parent):
        super(Message, self).__init__(parent)
        
        spacer = r.dimen.spacer
        
        label = '%s:' % r.string.view.message.to
        text = wx.StaticText(self, label=label)

        self.destination = wx.TextCtrl(self)
        
        self.toolBar = message.ToolBar(self)
        
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer2.Add(text, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3)
        sizer2.AddSpacer(spacer)
        sizer2.Add(self.destination, 1, wx.GROW)
        sizer2.AddSpacer(spacer)
        sizer2.Add(self.toolBar)
        
        self.message = message.Message(self)
        label = r.string.view.message.status
        self._statusLabel = label
        self.status = wx.StaticText(self, label=label % 0)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(sizer2, 0, wx.GROW)
        sizer.AddSpacer(2)
        sizer.Add(self.message, 1, wx.GROW)
        sizer.Add(self.status, 0, wx.ALIGN_RIGHT | wx.RIGHT, border=3)
        self.SetSizer(sizer)
        
        self.bind()
    
    def bind(self):
        self.Bind(wx.EVT_TEXT, self._onMessageChanged, self.message)
        self.Bind(wx.EVT_TEXT, self._onChanged, self.destination)
    
    _totalPdu = 0
    
    def _onMessageChanged(self, event):
        if event.String:
            pdus = messaging.sms.SmsSubmit('12345678', event.String).to_pdu()
            total = len(pdus)
            if self._totalPdu != total:
                self.status.Label = self._statusLabel % len(pdus)
                self._totalPdu = total
        else:
            self.status.Label = self._statusLabel % 0
            self._totalPdu = 0
        self._onChanged(event)
        
    _sendEnabled = False
    
    def _onChanged(self, event):
        enabled = bool(self.destination.Value) and bool(self.message.Value)
        if enabled != self._sendEnabled:
            self.toolBar.send.enable(enabled)
            self._sendEnabled = enabled
        event.Skip()

    _model = None
    
    @property
    def model(self):
        value = self.destination.Value
        self.model.numbers = [x.strip() for x in value.split(',')]
        return self._model
    
    @model.setter
    def model(self, value):
        self._model = value
        
        if value:
            self.destination.Value = ', '.join(value.numbers)
        else:
            self.destination.Value = ''
    